package com.tledu.web04.filter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

/**
 * 希望有登录之后的人才能访问这个系统
 *
 * @author cyrus
 */
//@WebFilter(urlPatterns = "/*")
public class LoginFilter extends HttpFilter {
    /**
     * 不需要登录就能访问的接口
     */
    private final List<String> skipUrlList =
            Arrays.asList("/login", "/login.jsp", "/register", "/register.jsp","/captcha");

    @Override
    protected void doFilter(HttpServletRequest req, HttpServletResponse res, FilterChain chain) throws IOException, ServletException {
        // 登录状态进行校验
        // 有些接口或者请求不需要登录就能访问
       System.out.println(this.getFilterConfig().getInitParameter("name"));
        String currentUri = req.getServletPath();
        if (skipUrlList.contains(currentUri)) {
            chain.doFilter(req, res);
            return;
        }
        // 判断登录状态
        HttpSession session = req.getSession();
        Boolean isLogin = (Boolean) session.getAttribute("isLogin");
        if (isLogin == null || !isLogin) {
            // 没有登录
            res.sendRedirect(req.getContextPath() + "/login.jsp");
            return;
        }
        // 登录了
        chain.doFilter(req, res);
    }
}
